package com.atguigu.demo2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author 孔德成
 * @Slogan 致敬大师，致敬未来的你
 * @date 2021/8/8
 */
public class Work2 {
    public static void main(String[] args) {
        Res res = new Res();
        new Thread(() -> {
            for (int i = 0; i < 52; i++) {
                res.printI();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 26; i++) {
                res.printC();
            }
        }, "B").start();
    }
}

class Res {
    // 记录 printI 线程工作次数
    int number = 0;
    int i = 1;
    char c = 65;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void printI() {

        lock.lock();
        try {
            // 判断 printI 线程工作次数
            while (number == 2) {
                condition.await();
            }
            // 工作
            System.out.println(i++);
            number++;
            // 通知
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {

        lock.lock();
        try {
            // 判断
            while (number != 2) {
                condition.await();
            }
            // 工作
            System.out.println(c++);
            // 重置 printI 线程的工作次数
            number = 0;
            // 通知
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}